<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 增加收货地址
 *
 * @author      Eden
 * @datetime    2016/12/2 19:34
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */


class Add_Model extends API_Model
{

    // 参数
    private $params = array();

    // 保存的值
    private $saveData = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {
            if (!$this->_checkParams()) {
                $send['error'] = $this->getError();
                break;
            }

            if (!empty($this->saveData['default'])) {
                $db = clone($this->db);
                $db->where('userId', $this->saveData['userId']);
                $db->update('user_address', ['default' => 0]);
            }

            $this->db->insert('user_address', $this->saveData);
            $lastId = $this->db->insert_id();

            if ($lastId) {
                $send['state'] = true;
                $this->saveData['userId'] = intval($this->saveData['userId']);
                $this->saveData['default'] = !empty($this->saveData['default']) ? true : false;
                $send['data'] = array_merge($this->saveData, array('id' => intval($lastId)));
                break;
            }

            $send['error'] = '保存失败';
        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     */
    private function _checkParams()
    {
        $needs = array('userId', 'name', 'phone', 'province', 'city', 'area', 'address', 'default');
        $data = array();

        if ($this->input->method(true) !== 'POST') {
             $this->setError('非法请求');
             return false;
        }

        foreach($needs as $need) {
            if (!array_key_exists($need, $this->params)) {
                $this->setError('参数错误');
                return false;
            }
            $data[$need] = $this->params[$need];
        }

        if (!checkPhone($this->params['phone'])) {
            $this->setError('手机号格式错误');
            return false;
        }

        $this->saveData = $data;
        return true;
    }

}
